package cn.weakup.thread.lock;

import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Dawn
 * @version 1.0.0
 * @desc
 * @date 2022/5/9
 */
public class ReentrantLockDemo {
    /**
     * 执行线程池
     */
    public static ExecutorService executor = new ThreadPoolExecutor(8, 16, 10,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000), new ThreadPoolExecutor.AbortPolicy());

    public static int count = 0;

    private static final Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(5000);
        for (int i = 0; i < 5000; i++) {
            executor.execute(()-> {
                // 在高并发下无锁的count++会出现并发问题
                //addNoLock();
                addByLock();
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();

        executor.shutdown();

        System.out.println(count);
    }

    private static void addNoLock() {
        count ++;
    }

    private static void addByLock() {
        lock.lock();
        try {
            count ++;
        } finally {
            lock.unlock();
        }

    }
}
